import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { CancelReq } from '../types';
import { Canceler } from 'axios';
const MAX_QUEUE = 10;
const initialState: CancelReq = {
  queue: [],
};

const cancelReqModule = createSlice({
  name: 'cancelReq',
  initialState,
  reducers: {
    enqueue: (state, action: PayloadAction<Canceler>) => {
      if (state.queue.length >= MAX_QUEUE) {
        state.queue.shift();
      }
      state.queue.push(action.payload);
    },
    clearQueue: (state) => {
      state.queue.forEach((reqCancel) => {
        reqCancel && reqCancel();
      });
      state.queue = [];
    },
  },
});

export const { enqueue, clearQueue } = cancelReqModule.actions;
export default cancelReqModule.reducer;
